package service

import (
	"fmt"
	"server/dao"
	"server/models"
	"strconv"
	"strings"
)

type Res struct {
	List  []*models.AdminUser
	Count int64
}

func GetUserList(page int64, perPage int64, name string, phone string, role_id string) (Res, error) {
	var res Res
	// 查询条件
	whereStr := []string{"status >= 0"}
	if name != "" {
		whereStr = append(whereStr, " AND name LIKE '%"+name+"%'")
	}
	if phone != "" {
		whereStr = append(whereStr, " AND phone LIKE '%"+phone+"%'")
	}

	// 查询拥有某角色的用户
	if role_id != "" {
		type Row struct {
			AdminRoleId uint32
			AdminUserId uint32
		}
		var rows []*Row
		dao.DB.Raw("SELECT * FROM `admin_user_role` WHERE `admin_user_role`.`admin_role_id` = ?", role_id).Scan(&rows)

		var rowIds []string
		for _, row := range rows {
			rowIds = append(rowIds, strconv.Itoa(int(row.AdminUserId)))
		}
		fmt.Printf("%#v\n%#v\n", rows, rowIds)
		whereStr = append(whereStr, " AND id IN ("+strings.Join(rowIds, ",")+")")
	}

	whereStrLong := strings.Join(whereStr, "")

	// 分页查询
	errFind := dao.DB.Model(&models.AdminUser{}).Select([]string{"id", "name", "phone", "status", "created_time", "updated_time"}).Where(whereStrLong).Offset(int(perPage * (page - 1))).Limit(int(perPage)).Preload("AdminRoles").Find(&res.List).Error
	if errFind != nil {
		return res, errFind
	}

	errCount := dao.DB.Model(&models.AdminUser{}).Where(whereStrLong).Count(&res.Count).Error
	if errCount != nil {
		return res, errCount
	}
	fmt.Printf("res: %#v\n", res)
	return res, nil
}
